package com.project.myPackage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.project.myPackage.common.R;
import com.project.myPackage.entity.Carts;
import com.project.myPackage.service.CartsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api(tags = "购物车管理")
@Slf4j
@RestController
@RequestMapping("/")

public class CartsController {
    @Autowired
    private CartsService cartsService;

    @ApiOperation(value = "根据用户id获取所有购物车信息")
    @RequestMapping("/getAllCartsByUserId")
    public R<?> getAllCartsByUserId(@RequestParam  Integer user_id) {
        List<Map<String, Object>> list = cartsService.getList(user_id);
        return  R.success(list,"获取所有购物车信息列表成功！");
    }

    @ApiOperation(value = "添加购物车")
    @PostMapping("/addCart")
    public R<?> addCart(@RequestBody Carts carts){
       // 判断购物车中是否有该商品
        LambdaQueryWrapper<Carts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Carts::getUser_id,carts.getUser_id())
                .eq(Carts::getProduct_id,carts.getProduct_id());
        List<Carts> list = cartsService.list(queryWrapper);
        if(list.size() == 0){
            boolean save = cartsService.save(carts);
            if (save) {
                return R.success("添加购物车成功！");
            } else {
                return R.error("添加购物车失败！");
            }
        }else{
          //"购物车中已存在该商品！则更新数量"
            Carts cart = list.get(0);//获取找到的商品
            //更新数量
            cart.setQuantity(cart.getQuantity()+carts.getQuantity());
            boolean update = cartsService.updateById(cart);
            if (update) {
                return R.success("更新购物车数量成功！");
            } else {
                return R.error("更新购物车数量失败！");
            }
        }
    }

    @ApiOperation(value = "删除购物车")
    @RequestMapping("/deleteCart")
    public R<?> deleteCart(Integer cart_id) {
        boolean remove = cartsService.removeById(cart_id);
        if (remove) {
            return R.success("删除购物车成功！");
        } else {
            return R.error("删除购物车失败！");
        }
    }

    @ApiOperation(value = "修改购物车")
    @PostMapping("/updateCart")
    public R<?> updateCart(@RequestBody  Carts carts) {
        boolean update = cartsService.updateById(carts);
        if (update) {
            return R.success("修改购物车成功！");
        } else {
            return R.error("修改购物车失败！");
        }
    }
}
